﻿#pragma execution_character_set("utf-8")

#include "mainwindow.h"

#include <QPushButton>
#include <QtWidgets>
#include <QLineEdit>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QFileDialog>
#include <QProgressBar>
#include <QNetworkAccessManager>
#include <QHttpMultiPart>
#include <QHttpPart>
#include <QNetworkRequest>
#include <QFile>
#include <QNetworkReply>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , selectFilePathButton(new QPushButton("选择文件路径"))
    , uploadButton(new QPushButton("上传"))
    , filePathEdit(new QLineEdit())
    , fileLayout(new QHBoxLayout())
    , mainLayout(new QVBoxLayout())
    , progressBar(new QProgressBar())

{
    InitUI();
    InitConnect();
}

MainWindow::~MainWindow()
{
}

void MainWindow::InitUI()
{
    QWidget *centerWidget = new QWidget(this);
    progressBar->hide();
    fileLayout->addWidget(selectFilePathButton) ;
    fileLayout->addWidget(filePathEdit);
    mainLayout->addLayout(fileLayout);
    mainLayout->addWidget(uploadButton);
    mainLayout->addWidget(progressBar);
    centerWidget->setLayout(mainLayout);
    mainLayout->addStretch();
    setCentralWidget(centerWidget);

}

void MainWindow::InitConnect()
{
    connect(selectFilePathButton,&QPushButton::clicked,this,&MainWindow::slotSelectFilePath);
    connect(uploadButton,&QPushButton::clicked,this,&MainWindow::slotSelectUploadFile);
    connect(&uploadFileManager,&UploadFileManager::sigUploadProgress,this,&MainWindow::slotUploadProgress);
    connect(&uploadFileManager,&UploadFileManager::sigFinish,this,&MainWindow::slotUploadFinished);
}

void MainWindow::slotSelectFilePath()
{

    QString filePath = QFileDialog::getOpenFileName(this);
    filePathEdit->setText(filePath);
}

void MainWindow::slotSelectUploadFile()
{
    uploadButton->setDisabled(true);
    progressBar->show();
    uploadFileManager.UploadFile("http://test.open-ssl.cn/upload.php",filePathEdit->text());
}

void MainWindow::slotUploadFinished(QNetworkReply::NetworkError status)
{
    uploadButton->setDisabled(false);
    progressBar->hide();
    if (status == QNetworkReply::NoError) {
        qInfo() << "upload success!";

    } else {
        qInfo() << "upload failed:";

    }
}


void MainWindow::slotUploadProgress(int value)
{
    progressBar->setValue(value);
}

